package dijjer.io.xfer.http.handlers;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.Map;
import dijjer.Dijjer;
import dijjer.io.xfer.http.HTTPException;
import dijjer.io.xfer.http.HTTPExceptionResponse;
import dijjer.io.xfer.http.HTTPResponse;
import dijjer.io.xfer.http.PageHandler;
import dijjer.updater.Loader;
import dijjer.util.logging.Logger;

public class UpdateHandler extends PageHandler {

	public static final String VERSION = "$Id: UpdateHandler.java 2 2008-03-21 14:33:03Z ian.clarke $";
	public final static String CRLF = "\r\n";

	public HTTPResponse handleRequest(String method, String url, Map params, Map headers, Reader in)
	{
		try {
			try {
				Loader.reload(Dijjer.BUILD + 1, true);
			} catch (Exception e) {
				Logger.error(e);
				return dumpError(HttpURLConnection.HTTP_OK, "Could not update",
				    "Dijjer could not update or no newer build found.");
			}
			
			return new HTTPResponse(HttpURLConnection.HTTP_OK, "OK", "Reload Successful") {

				String output =
				    "<html><head><title>Reload Successful</title>"
				    + "<style type=\"text/css\">"
				    + "body { background: #FAFAFA; font-family: Verdana, Arial, sans-serif; font-size: 11px;}"
				    + "td { background: #FAFAFA; font-family: Verdana, Arial, sans-serif; font-size: 11px;}"
				    + "a {color:#000000; text-decoration: none;}"
				    + "a:hover {color:#822D2F; text-decoration: none;}"
				    + "</style>"
				    + "</head><body>"
				    + "<h1>Update Successful!</h1>"
				    + "<a href=\"/\">Click here to see the updated status page</a> "
				    + "(Note, you may have to reload the page in your browser)"
				    + "</body></html>";

				protected long getContentLength() {
					return output.length();
				}

				protected void writeTo(OutputStream out) throws IOException {
					out.write(output.getBytes());
				}
			};

		} catch (Exception e) {
			Logger.error(e);
			try {
				return new HTTPExceptionResponse(e);
			} catch (IOException ex) {
				throw new HTTPException(HttpURLConnection.HTTP_INTERNAL_ERROR, "Internal Error",
					ex.getMessage());
			}
		}
	}
}
